<script setup lang="ts">
import { reactive } from 'vue'
import { register } from '../../api/user'
import type { IRegister } from '../../types/data'
import { showToast } from 'vant';
import router from '@/router';
defineOptions({ name: 'registerPage' })


const registerForm = reactive<IRegister>({
  username: '',
  password: '',
  rePassword: ''
});

const registerAPI = async (val: IRegister) => {
  try {
    delete val.rePassword
    await register(val)
    showToast('注册成功');
    router.push('/login')
  } catch (err) {
    console.log(err)
  }
}
</script>
<template>
  <van-nav-bar title="注册"></van-nav-bar>
  <van-form @submit="registerAPI">
    <van-cell-group inset>
      <van-field v-model="registerForm.username" name="username" label="用户名" placeholder="用户名"
        :rules="[{ required: true, message: '请填写用户名' }, { pattern: /^\w{6,16}$/, message: '密码格式错误' }]" />
      <van-field v-model="registerForm.password" name="password" type="password" label="密码" placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }, { pattern: /^\w{6,16}$/, message: '密码格式错误' }]" />
      <van-field v-model="registerForm.rePassword" name="rePassword" type="password" label="重复密码" placeholder="再次输入密码"
        :rules="[{ required: true, message: '请再次输入密码' },
        {validator(val:string){
          if(val === registerForm.password){
            return true
          }else{
            return '两次密码不一致'
          }
        }}
      ]" />
    </van-cell-group>
    <div style="margin: 16px;">
      <van-button round block type="primary" native-type="submit">
        注册
      </van-button>
    </div>
    <van-row justify="end">
      <router-link class="link" to="/login">已有账号去登录</router-link>
    </van-row>

  </van-form>
</template>
  <script lang="ts" setup>
  
  </script>
<style scoped lang="scss">
.link {
  color: #069;
  font-size: 12px;
  padding-right: 20px;
}
</style>